package com.anlu.concurrent.utils;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.*;

/**
 * <p>
 * Description:TODO 详细描述
 * <p>
 * Copyright: 天津联想协同科技有限公司
 * <p>
 *
 * @author anlu
 * @date 2021/10/27 17:40
 */
public class ThreadPoolUtils {
    private static ThreadPoolExecutor threadPool = null;

    static {
        int corePoolSize = Runtime.getRuntime().availableProcessors();
        int maxPoolSize = Runtime.getRuntime().availableProcessors() * 2;
        long keepAliveTime = 5;
        TimeUnit keepAliveTimeUnit = TimeUnit.MINUTES;
        int queSize = 100_000;
//        private final int POOL_SIZE = Runtime.getRuntime().availableProcessors();

        ThreadFactory threadFactory = new ThreadFactoryBuilder()
                .setNameFormat("ThreadPoolUtils")
                .build();

        /**
         * int corePoolSize,
         *                               int maximumPoolSize,
         *                               long keepAliveTime,
         *                               TimeUnit unit,
         *                               BlockingQueue<Runnable> workQueue,
         *                               ThreadFactory threadFactory
         */

        ArrayBlockingQueue arrayBlockingQueue =  new ArrayBlockingQueue<>(queSize);
        if(threadPool==null){
            threadPool = new ThreadPoolExecutor(corePoolSize, maxPoolSize,keepAliveTime,keepAliveTimeUnit,arrayBlockingQueue,threadFactory);
        }
    }


    /**
     * 获取线程池
     * @return 线程池
     */
    public static ThreadPoolExecutor getThreadPool() {
        return threadPool;
    }

}
